package io.github.bigbird0101.pipeline;

import java.util.function.Predicate;

public abstract class AbstractPredicateObjectHandler<T> implements ObjectHandler<T> {
    private final Predicate<T>[] predicates;

    public AbstractPredicateObjectHandler(Predicate<T>... predicates) {
        this.predicates = predicates;
    }

    public Predicate<T>[] getPredicates() {
        return predicates;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void handle(HandlerContext context, T object) {
        for(Predicate<T> predicate:predicates){
          if(!predicate.test(object)){
              return;
          }
        }
        Handler handler = context.getPipeline().getNext(this).orElse(null);
        if(!(handler instanceof ObjectHandler)){
            return;
        }
        T handleObject=doHandle(context,object);
        if(handleObject==object
               && context instanceof EventHandlerContext){
                EventHandlerContext eventHandlerContext= (EventHandlerContext) context;
                eventHandlerContext.sendEvent(new HandlerEvent(handleObject) {
                    @Override
                    public Object getSource() {
                        return super.getSource();
                    }
                });
        }else if(null!=handleObject) {
            ((ObjectHandler<T>) handler).handle(context, handleObject);
        }
    }

    protected abstract T doHandle(HandlerContext context, T object);
}
